package com.hoshiicloud.mallshop.service.impl.goodsmanage;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.goods.entity.goods.Gallery;
import com.hoshiicloud.goods.entity.goods.GoodsGallery;
import com.hoshiicloud.goods.entity.sku.BaseSku;
import com.hoshiicloud.goods.entity.sku.ExtSku;
import com.hoshiicloud.goods.entity.spu.BaseGoodsGallery;
import com.hoshiicloud.goods.entity.spu.BaseSpu;
import com.hoshiicloud.goods.entity.spu.ExtSpu;
import com.hoshiicloud.goods.entity.spu.ExtSpuTags;
import com.hoshiicloud.goods.param.sku.*;
import com.hoshiicloud.goods.param.spu.BaseSpuAddParam;
import com.hoshiicloud.goods.param.spu.ExtSpuAddParam;
import com.hoshiicloud.goods.param.spu.SpuSalesCategoryAddParam;
import com.hoshiicloud.goods.vo.GoodsPropertiesVo;
import com.hoshiicloud.mallshop.feign.ShopGoods2FeignService;
import com.hoshiicloud.mallshop.feign.ShopGoodsSpuSkuFeignService;
import com.hoshiicloud.mallshop.feign.ShopIdGeneratorService;
import com.hoshiicloud.mallshop.feign.ShopUserFeignService;
import com.hoshiicloud.mallshop.param.ProductSkuParam;
import com.hoshiicloud.mallshop.param.ProductSpuParam;
import com.hoshiicloud.mallshop.service.goodsmanage.GoodsReleaseService;
import com.hoshiicloud.user.entity.store.PlatStore;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 店铺商品发布Service实现类
 *
 * @author linjx on 2019/9/16
 */
@Service
@Slf4j
public class GoodsReleaseServiceImpl implements GoodsReleaseService {

    private final ShopGoodsSpuSkuFeignService spuSkuFeignService;
    private final ShopGoods2FeignService goods2FeignService;
    private final ShopUserFeignService shopUserFeignService;
    private final ShopIdGeneratorService idGeneratorService;

    public GoodsReleaseServiceImpl(ShopGoodsSpuSkuFeignService spuSkuFeignService, ShopGoods2FeignService goods2FeignService, ShopUserFeignService shopUserFeignService, ShopIdGeneratorService idGeneratorService) {
        this.spuSkuFeignService = spuSkuFeignService;
        this.goods2FeignService = goods2FeignService;
        this.shopUserFeignService = shopUserFeignService;
        this.idGeneratorService = idGeneratorService;
    }

    /**
     * 商品发布前的数据准备
     */
    @Override
    public Map<String, Object> publishPreData(Long categoryId, Map<String, Object> myMap) {

        Map<String, Object> map = new HashMap<>();
        Long companyId = Long.valueOf(myMap.get("companyId").toString());
        // 类目属性
        List<GoodsPropertiesVo> properties = spuSkuFeignService.getProperByCateId(categoryId, companyId).getData();
        // 包装单位
        String propertyName = "包装单位";
        List<String> packagings = spuSkuFeignService.dropdownBox(companyId, propertyName).getData();
        // 销售单位
        String propertyNameSales = "销售单位";
        List<String> sales = spuSkuFeignService.dropdownBox(companyId, propertyNameSales).getData();
        // 品牌
        List<Map<String, Object>> brand = spuSkuFeignService.getGoodsBrandsByCateId(categoryId).getData();
        // 商品标签
        List<String> extSpuTagsSelect = Arrays.asList("新鲜", "有机", "无残留");
        // 根据店铺Id, 查询店铺类型 国内还是跨境 1.B2C(国内) 2.B2C（国外）3.C2C 4.O2O' (1,3,4 国内)
        PlatStore platStore = shopUserFeignService.getPlatStoreById(Long.parseLong(myMap.get("storeId") + "")).getData();

        Integer type = platStore.getType();
        Integer purchaseType = type == null ? 1 : type == 2 ? 2 : 1;

        map.put("purchaseType", purchaseType);
        map.put("properties", properties);
        map.put("sales", sales);
        map.put("packagings", packagings);
        map.put("brand", brand);
        map.put("extSpuTagsSelect", extSpuTagsSelect);
        return map;
    }

    /**
     * 商品发布
     */
    @Override
    public Boolean saveGoods(ProductSpuParam spuParam) {
        // 保存 BaseSpu
        BaseSpu baseSpu = this.saveBaseSpu(spuParam);
        // 保存ExtSpu
        this.saveExtSpu(spuParam);
        // 保存营销类目信息
        this.saveSpuSalesCategory(spuParam);
        // 保存标签信息
        this.saveExtSpuTags(spuParam);
        // 保存相册信息 以及保存 baseSpu 和 extSpu 与相册相关联的信息
        this.saveGalleryAndRelation(spuParam);

        // 保存 sku的相关信息
        String spuNo = baseSpu.getSpuNo();
        String skuCode = "";
        List<ProductSkuParam> skuList = spuParam.getSkuList();
        for (ProductSkuParam skuParam : skuList) {
            // 生成sku编码
            String skuNo = this.createSkuCode(spuNo, skuCode);
            skuParam.setSkuNo(skuNo);
            // 保存baseSku
            this.saveBaseSku(spuParam, skuParam);
            // 保存baseSku的图片信息
            this.saveBaseSkuGallery(spuParam, skuParam);
            // 保存VendorGoodsSku
            this.saveVendorGoodsSku(spuParam, skuParam);
            // 保存extSku
           this.saveExtSku(spuParam, skuParam);
            // 保存productManage
            this.saveProductManage(spuParam, skuParam);

            skuCode = skuNo;
        }
        return null;
    }

    // =============================保存spu相关信息=============================

    private BaseSpu saveBaseSpu(ProductSpuParam spuParam) {

        // 设置需要保存的BaseSpu的相关值
        BaseSpuAddParam baseSpuAddParam = this.setBaseSpuAddParam(spuParam);
        // 设置categoryContext
        String categoryIdStr = StringUtils.join(spuParam.getCategoryArr(), "\',\'");
        String categoryContextQueryStr = "\'" + categoryIdStr + "\'";
        String categoryContext = spuSkuFeignService.getCategoryContext(categoryContextQueryStr).getData();
        baseSpuAddParam.setCategoryContext(categoryContext);
        BaseSpu baseSpu = spuSkuFeignService.saveBaseSpu(baseSpuAddParam).getData();

        // 设置baseSpu的Id
        spuParam.setBaseSpuId(baseSpu.getId());
        return baseSpu;

    }

    private void saveExtSpu(ProductSpuParam spuParam) {

        ExtSpuAddParam extSpuAddParam = this.setExtSpuAddParam(spuParam);
        // 设置权重: 为该店铺最大权重+1
        Long maxWeight = spuSkuFeignService.getExtSpuMaxWeight(spuParam.getStoreId()).getData();
        extSpuAddParam.setWeight(++maxWeight);
        ExtSpu extSpu = spuSkuFeignService.saveExtSpu(extSpuAddParam).getData();

        // 为 spuParam 设置ExtSpu的Id
        spuParam.setExtSpuId(extSpu.getId());
    }

    private void saveSpuSalesCategory(ProductSpuParam spuParam) {

        SpuSalesCategoryAddParam categoryAddParam = new SpuSalesCategoryAddParam();
        // 类目Id
        categoryAddParam.setSalesCategoryId(spuParam.getCategoryId());
        // BaseSpuId
        categoryAddParam.setBaseSpuId(spuParam.getBaseSpuId());
        // ExtSpuId
        categoryAddParam.setExtSpuId(spuParam.getExtSpuId());
        // 创建人
        categoryAddParam.setCreatedBy(spuParam.getCreateBy());
        goods2FeignService.spuSalesCategoryAdd(categoryAddParam);
    }

    private void saveExtSpuTags(ProductSpuParam spuParam) {

        List<ExtSpuTags> extSpuTagsList = new ArrayList<>();
        List<String> extSpuTags = spuParam.getExtSpuTags();
        for (String tagName : extSpuTags) {

            ExtSpuTags extspuTag = new ExtSpuTags();
            // 生成Id
            Long tagId = this.getId();
            extspuTag.setId(tagId);
            // ExtSpuId
            extspuTag.setSpuId(spuParam.getExtSpuId());
            // BaseSpuId
            extspuTag.setBaseSpuId(spuParam.getBaseSpuId());
            // 标签名称
            extspuTag.setTagName(tagName);
            // 创建人
            extspuTag.setCreatedBy(spuParam.getCreateBy());
            // 创建时间
            extspuTag.setCreatedTime(LocalDateTime.now());
            extSpuTagsList.add(extspuTag);
        }
        goods2FeignService.saveExtSpuTagsBatch(extSpuTagsList);
    }

    private void saveGalleryAndRelation(ProductSpuParam spuParam) {

        String imagesStr = spuParam.getDefaultImage();
        String[] images = imagesStr.split(",");

        // 保存相册信息
        List<Gallery> galleryList = new ArrayList<>();
        for (String image : images) {
            Long galleryId = this.getId();
            Gallery gallery = new Gallery();
            gallery.setId(galleryId);
            gallery.setImgUrl(image);
            gallery.setCreateTime(LocalDateTime.now());
            galleryList.add(gallery);
        }
        spuSkuFeignService.saveGalleryBath(galleryList);

        // 保存BaseSpu与 相册的关联信息
        List<BaseGoodsGallery> baseGoodsGalleryList = new ArrayList<>();
        for (Gallery gallery : galleryList) {
            Long baseGoodsGalleryId = this.getId();
            BaseGoodsGallery baseGoodsGallery = new BaseGoodsGallery();
            baseGoodsGallery.setId(baseGoodsGalleryId);
            baseGoodsGallery.setGoodsId(spuParam.getBaseSpuId());
            baseGoodsGallery.setGalleryId(gallery.getId());
            baseGoodsGallery.setCreateTime(gallery.getCreateTime());
            baseGoodsGalleryList.add(baseGoodsGallery);
        }
        spuSkuFeignService.saveBaseGoodsGalleryBatch(baseGoodsGalleryList);

        // 保存ExtSpu与相册的关联信息
        List<GoodsGallery> goodsGalleryList = new ArrayList<>();
        for (Gallery gallery : galleryList) {
            GoodsGallery goodsGallery = new GoodsGallery();
            Long goodsGalleryId = this.getId();
            goodsGallery.setId(goodsGalleryId);
            goodsGallery.setExtSpuId(spuParam.getExtSpuId());
            goodsGallery.setBaseSpuId(spuParam.getBaseSpuId());
            goodsGallery.setGalleryId(gallery.getId());
            goodsGalleryList.add(goodsGallery);
        }
        goods2FeignService.saveGoodsGalleryBatch(goodsGalleryList);

    }

    // =============================保存sku相关信息=============================

    private void saveBaseSku(ProductSpuParam spuParam, ProductSkuParam skuParam) {
        BaseSkuAddParam baseSkuAddParam = this.setBaseSkuAddParam(spuParam, skuParam);
        BaseSku baseSku = spuSkuFeignService.saveBaseSku(baseSkuAddParam).getData();

        // 为skuParam 的 baseSkuId赋值
        skuParam.setBaseSkuId(baseSku.getId());
    }

    private void saveBaseSkuGallery(ProductSpuParam spuParam, ProductSkuParam skuParam) {
        BaseSkuGalleryAddParam addParam = new BaseSkuGalleryAddParam();
        addParam.setSkuId(skuParam.getBaseSkuId());
        addParam.setImageType(1);
        addParam.setImage(skuParam.getSkuImage());
        addParam.setCreatedBy(spuParam.getCreateBy());
        spuSkuFeignService.saveBaseSkuGallery(addParam);
    }

    private void saveVendorGoodsSku(ProductSpuParam spuParam, ProductSkuParam skuParam) {

        VendorGoodsSkuAddParam vendorGoodsSku = this.setVendorGoodsSkuAdd(spuParam, skuParam);
        spuSkuFeignService.saveVendorGoodsSku(vendorGoodsSku);
    }

    private void saveExtSku(ProductSpuParam spuParam, ProductSkuParam skuParam) {
        ExtSkuAddParam extSkuAddParam = this.setExtSkuAddParam(spuParam, skuParam);
        ExtSku extSku = spuSkuFeignService.saveExtSku(extSkuAddParam).getData();

        // 设置ExtSku的Id
        skuParam.setExtSkuId(extSku.getId());
    }

    private void saveProductManage(ProductSpuParam spuParam, ProductSkuParam skuParam) {
        ProductManageAddParam productManageAddParam = this.setProductManageAddParam(spuParam, skuParam);
        spuSkuFeignService.saveProductManage(productManageAddParam);
    }

    // =============================编码以及Id生成=============================

    /**
     * spu编码生成 类目编码+商品类型+年月日（各取2位）+秒数（创建时间时分秒转换成秒数）+7位随机数
     */
    private String creteSpuCode(String categoryCode, Integer purchaseType, LocalDateTime createTime) {
        StringBuffer spuCode = new StringBuffer(categoryCode.replace(",", ""));
        spuCode.append(purchaseType);
        spuCode.append(DateTimeFormatter.ofPattern("yyMMdd").format(createTime));
        spuCode.append(createTime.toLocalTime().toSecondOfDay());
        spuCode.append(ThreadLocalRandom.current().nextInt(1000000, 9999999));
        return spuCode.toString();
    }

    /**
     * sku编码生成 SPU_CODE+序号（最大99，从01开始）
     */
    private String createSkuCode(String spuNo, String skuNo) {
        if (StringUtils.isBlank(skuNo)) {
            return spuNo + "01";
        } else {
            // 截取skuNo后两位
            String numStr = skuNo.substring(spuNo.length() - 2);
            // 自增1
            long num = Long.parseLong(numStr);
            String lastNo = String.format("%02d", ++num);
            // 截取原先skuNo 除了后两位的前面的位数
            String baseNo = spuNo.substring(0, spuNo.length() - 2);
            return baseNo + lastNo;
        }
    }

    /**
     * 生成一个Id 并且返回
     */
    private Long getId() {
        String id = idGeneratorService.queryGeneratorId();
        if (StrUtil.isBlank(id)) {
            throw new ServiceException(CommonError.error("主键ID生成失败"));
        }
        return Long.parseLong(id);
    }

    // =============================相关字段的设置=============================

    private BaseSpuAddParam setBaseSpuAddParam(ProductSpuParam spuParam) {
        String spuNo = this.creteSpuCode(StringUtils.join(spuParam.getCategoryArr()), spuParam.getPurchaseType(), LocalDateTime.now());
        BaseSpuAddParam baseSpu = new BaseSpuAddParam();
        // 租户Id
        baseSpu.setCompanyId(spuParam.getCompanyId());
        // 平台Id
        baseSpu.setPlatformId(spuParam.getPlatformId());
        // 店铺Id
        baseSpu.setStoreId(spuParam.getStoreId());
        // 创建人
        baseSpu.setCreatedBy(spuParam.getCreateBy());
        // 商品编码
        baseSpu.setSpuNo(spuNo);
        // 商品名称
        baseSpu.setTitle(spuParam.getTitle());
        // 商品类目Id
        baseSpu.setCategoryId(spuParam.getCategoryArr()[spuParam.getCategoryArr().length - 1]);
        // 类目描述
        baseSpu.setCategoryDescribe(StringUtils.join(spuParam.getCategoryArr(), ","));
        // 品牌
        baseSpu.setBrandId(spuParam.getBrandId());
        // 商品类型
        baseSpu.setProductType(spuParam.getProductType());
        // 采购类型
        baseSpu.setPurchaseType(spuParam.getPurchaseType());
        // 属性
        baseSpu.setExtendProperty(spuParam.getExtendProperty());
        // 默认图片
        baseSpu.setDefaultImage(spuParam.getDefaultImage().split(",")[0]);
        // 1-共有 2-私有
        baseSpu.setPublished(1);
        // 上下架状态
        baseSpu.setStatus(1);

        // 规格
        Map<String, Object> map = new HashMap<>();
        map.put("spec_id", 3263976614391709706L);
        map.put("spec_name", "默认");
        map.put("spec_itemid", 3263976614391709716L);
        map.put("spec_itemname", "默认");
        Map<String, Object> map2 = new HashMap<>();
        map2.put("spec1", map);
        baseSpu.setExtendSpec(JSONObject.toJSONString(map));
        return baseSpu;
    }

    private ExtSpuAddParam setExtSpuAddParam(ProductSpuParam spuParam) {

        ExtSpuAddParam extSpuParam = new ExtSpuAddParam();

        // 租户Id
        extSpuParam.setCompanyId(spuParam.getCompanyId());
        // 平台Id
        extSpuParam.setPlatformId(spuParam.getPlatformId());
        // 店铺Id
        extSpuParam.setStoreId(spuParam.getStoreId());
        // 创建人
        extSpuParam.setCreatedBy(spuParam.getCreateBy());
        // spuId
        extSpuParam.setSpuId(spuParam.getBaseSpuId());
        // 商品标题
        extSpuParam.setTitle(spuParam.getTitle());
        // 存储商品主图
        extSpuParam.setSpuImage(spuParam.getDefaultImage().split(",")[0]);
        // 主图视频
        extSpuParam.setSpuVideo(spuParam.getSpuVideo());
        // 图文描述
        extSpuParam.setSpuDescription(spuParam.getSpuDescription());
        // 售后说明
        extSpuParam.setServiceDescription(spuParam.getServiceDescription());
        // 购买须知
        extSpuParam.setNotice(spuParam.getNotice());
        // 横图
        extSpuParam.setHImage(spuParam.getHeImage());
        // 竖图
        extSpuParam.setVImage(spuParam.getVeImage());
        // 设置上下架状态
        extSpuParam.setStatus(spuParam.getStatus());
        // 设置上架或下架时间
        if (spuParam.getStatus() == 1) {
            extSpuParam.setUpTime(LocalDateTime.now());
        } else {
            extSpuParam.setDownTime(LocalDateTime.now());
        }
        return extSpuParam;
    }

    private BaseSkuAddParam setBaseSkuAddParam(ProductSpuParam spuParam, ProductSkuParam skuParam) {
        return BaseSkuAddParam.builder()
                // 租户Id
                .companyId(spuParam.getCompanyId())
                // 平台Id
                .platformId(spuParam.getPlatformId())
                // 店铺Id
                .storeId(spuParam.getStoreId())
                // 创建人
                .createdBy(spuParam.getCreateBy())
                // 商品编码
                .skuNo(skuParam.getSkuNo())
                // BaseSpuId
                .spuId(spuParam.getBaseSpuId())
                // 商品标题
                .skuTitle(spuParam.getTitle())
                // 销售单位（*）
                .salesUnit(skuParam.getSalesUnit())
                // 条形码
                .barCode(skuParam.getBarCode())
                // 箱码
                .packetCode(skuParam.getPacketCode())
                // 规格
                .extendSpec(skuParam.getExtendSpec())
                // 是否负库存(无用)
                .isStored(0)
                // 是否允许分销 0-不允许分销 1-允许分销
                .distributorStatu(skuParam.getDistributorStatu())
                // 是否允许分店编辑售价 0-不允许 1-允许
                .editStatu(skuParam.getEditStatu())
                // 上下架状态
                .status(1).build();
    }

    private VendorGoodsSkuAddParam setVendorGoodsSkuAdd(ProductSpuParam spuParam, ProductSkuParam skuParam) {

        return VendorGoodsSkuAddParam.builder()
                .companyId(spuParam.getCompanyId())
                .platformId(spuParam.getPlatformId())
                .storeId(spuParam.getStoreId())
                .createdBy(spuParam.getCreateBy())
                // skuId
                .skuId(skuParam.getBaseSkuId())
                // spuId
                .spuId(spuParam.getBaseSpuId())
                // 条形码
                .barCode(skuParam.getBarCode())
                // 箱码
                .packetCode(skuParam.getPacketCode())
                // 包装单位
                .packetUnit(skuParam.getPacketUnit())
                // 内件数
                .innerBoxs(skuParam.getInnerBoxs())
                // 商品重量
                .weight(skuParam.getWeight())
                // 供价（不含税）
                .unitPrice(skuParam.getUnitprice())
                // 供价（含税）
                .taxUnitprice(skuParam.getTaxUnitprice())
                // 增值税率
                .taxRate(skuParam.getTaxRate())
                // 采购类型
                .vendorPoType(skuParam.getVendorPoType())
                // 供应商Id
                .vendorId(skuParam.getVendorId())
                .build();
    }

    private ExtSkuAddParam setExtSkuAddParam(ProductSpuParam spuParam, ProductSkuParam skuParam) {

        Map<String, Object> map = new HashMap<>();
        map.put("spec_id", 3263976614391709706L);
        map.put("spec_name", "默认");
        map.put("spec_itemid", 3263976614391709716L);
        map.put("spec_itemname", "默认");
        Map<String, Object> map2 = new HashMap<>();
        map2.put("spec1", map);

        Integer status = spuParam.getStatus() == 1? 2: 3;

        return ExtSkuAddParam.builder()
                // 租户Id
                .companyId(spuParam.getCompanyId())
                // 平台Id
                .platformId(spuParam.getPlatformId())
                // 店铺Id
                .storeId(spuParam.getStoreId())
                // 创建人
                .createdBy(spuParam.getCreateBy())
                // ExtSpuId
                .spuId(spuParam.getExtSpuId())
                // BaseSkuId
                .skuId(skuParam.getBaseSkuId())
                // 商品名称
                .skuTitle(spuParam.getTitle())
                // sku图片
                .skuImage(spuParam.getDefaultImage().split(",")[0])
                // 售价
                .salePrice(skuParam.getSalePrice())
                // 市场价
                .marketPrice(skuParam.getMarketPrice())
                // 成本价
                .costPrice(skuParam.getCostPrice())
                // 是否库库存足够才能下单  1 是 0 否
                .storeEnough(1)
                // 属性
                .extendProperty(spuParam.getExtendProperty())
                // 规格
                .extendSpec(JSONObject.toJSONString(map2))
                // 上下架状态 2-上架  3-下架
                .status(status)
                // 收货间隔时间
                .receiptInterval(skuParam.getReceiptInterval())
                // 提货时间
                .receiptDate(skuParam.getReceiptDate()).build();
    }

    private ProductManageAddParam setProductManageAddParam(ProductSpuParam spuParam, ProductSkuParam skuParam) {

        return ProductManageAddParam.builder()
                // 租户Id
                .companyId(spuParam.getCompanyId())
                // 平台Id
                .platformId(spuParam.getPlatformId())
                // 店铺Id
                .storeId(spuParam.getStoreId())
                // 创建人
                .createdBy(spuParam.getCreateBy())
                // 商品编码
                .skuNo(skuParam.getSkuNo())
                // BaseSkuId
                .baseSkuId(skuParam.getBaseSkuId())
                // ExtSkuId
                .skuId(skuParam.getExtSkuId())
                // 商品名称
                .skuName(spuParam.getTitle())
                // 分配数量
                .quantity(new BigDecimal(skuParam.getQuantity()))
                // 单位
                .unit(skuParam.getPacketUnit())
                // 来源
                .source(0)
                // 冻结数量
                .freezes(BigDecimal.ZERO).build();
    }
}
